package client;

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.security.PublicKey;
import java.text.SimpleDateFormat;
import java.util.Date;

import encryption.RSAEncryptor;

public class Transmitter extends Thread {
	
	private static final int PORT_RECEP_LOW = 5160;
	private static final int PORT_RECEP_HIGH = 5170;
	
	private static final String recepAddress = "localhost";
	
	private String trama;
	private String tipo;
	
	private SimpleDateFormat sdf;
	
	public Transmitter(String trama, String tipo){
		
		this.trama = trama;
		this.tipo = tipo;
		
		sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
	}
	
	public void run(){
		
		try {
			
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(RSAEncryptor.PUBLIC_KEY_FILE));
			PublicKey publicKey = (PublicKey) ois.readObject();
			ois.close();
			
			byte[] encryptedFrame = RSAEncryptor.encrypt(trama, publicKey);
						
			DatagramSocket socket = new DatagramSocket();		
			
			InetAddress address = InetAddress.getByName(recepAddress);
			if(tipo.equals("normal")){
				DatagramPacket packet = new DatagramPacket(encryptedFrame, encryptedFrame.length, address, PORT_RECEP_LOW);
				socket.send(packet);
			}
			else if(tipo.equals("alerta")){				
				DatagramPacket packet = new DatagramPacket(encryptedFrame, encryptedFrame.length, address, PORT_RECEP_HIGH);
				socket.send(packet);
				System.out.println(trama + " alerta enviada " + sdf.format(new Date()));
			}
			
			
			
			
			socket.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		} 
		
	}

}
